import { Module } from '@nestjs/common';
import { ImageUploadController } from './imageUpload.controller';
import { MulterModule } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { ImageUploadService } from './image-upload.service';
const fs = require('fs-extra')  // 这里只能使用require，否则会报错

@Module({
  imports: [
    MulterModule.register({
      storage: diskStorage({
        destination: function (req, file, callback) {
          // 将文件按照年-月、日分别创建文件夹存储
          const date = new Date();
          const year = date.getFullYear();
          const month = ('0' + (date.getMonth() + 1)).slice(-2);
          const day = ('0' + date.getDate()).slice(-2);
          const destination = join(
            __dirname,
            '../../../images',
            year + '-' + month,
            day,
          );
          // 确保路径存在，否则自动创建目录
          fs.ensureDir(destination).then(res => {
            callback(null, destination);
          })
        },
        filename: (req, file, callback) => {
          const fileName = `${
            new Date().getTime() + extname(file.originalname)
          }`;
          return callback(null, fileName);
        },
      }),
    }),
  ],
  controllers: [ImageUploadController],
  providers: [ImageUploadService],
  exports:[ImageUploadService]
})
export class ImageUploadModule {}
